<script>
import Taro from "@tarojs/taro";
import { reactive } from "vue";
import { useTzRouter } from "@/vhooks/useTzRouter";

export default {
  name: "SingleShot",
  components: {},
  setup() {
    const state = reactive({
      basePath: "",
      pdfCode: "",
      files: [],
      docCode: "",
      filePathList: [],
    });
    const { route } = useTzRouter();
    const { basePath, pdfCode, docCode } = route.query;
    let files = route.query.files;
    files = files.split(",");
    Object.assign(state, { basePath, pdfCode, files, docCode });
    state.filePathList = files.map((item) => basePath + item);

    const imgRender = () => {
      const { files, basePath } = state;

      const handlePreview = (url) => {
        Taro.previewImage({
          current: url, // 当前图片
          urls: state.filePathList, // 所有图片
        });
      };

      if (files && files.length) {
        return (
          <tz-view class="img-content">
            {files.map((item) => (
              <tz-image
                show-menu-by-longpress
                src={basePath + item}
                key={item}
                onClick={() => handlePreview(basePath + item)}
              ></tz-image>
            ))}
          </tz-view>
        );
      }
      return;
    };

    const handleDownload = () => {
      state.downLoadBtnDisabled = true;
      const { basePath, pdfCode, docCode } = state;
      Taro.downloadFile({
        url: basePath + pdfCode,
        filePath: Taro.env.USER_DATA_PATH + "/" + docCode + "确报单一截图.pdf",
      })
        .then((res) => {
          Taro.openDocument({
            filePath: res.filePath,
            showMenu: true,
            fileType: "pdf",
            complete() {
              state.downLoadBtnDisabled = false;
            },
          });
        })
        .catch(() => {
          state.downLoadBtnDisabled = false;
        });
    };

    return () => {
      return (
        <tz-view class="single-shot">
          <tz-view class="show-bar">
            <tz-view>
              图片：共 {state.files ? state.files.length : 0} 张
            </tz-view>
            <tz-button
              disabled={state.downLoadBtnDisabled}
              type="default"
              onClick={() => handleDownload()}
            >
              PDF下载
            </tz-button>
          </tz-view>
          <tz-view class="tip-text">温馨提示：长按以下截图保存到手机</tz-view>
          {imgRender()}
        </tz-view>
      );
    };
  },
};
</script>

<style lang="scss">
.single-shot {
  display: flex;
  align-items: center;
  flex-direction: column;
  .show-bar {
    display: flex;
    align-items: center;
    font-size: 15px;
    padding: 10px;
    .tz-button {
      height: 30px;
      width: 80px;
      margin-left: 10px;
    }
  }
  .tip-text {
    font-size: 15px;
    padding-bottom: 10px;
  }
  .img-content {
    text-align: center;
  }
}
</style>
